package org.example.springboot.controller;

import org.example.springboot.common.Result;
import org.example.springboot.entity.Need;
import org.example.springboot.service.NeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/need")
public class NeedController {

    @Autowired
    NeedService Service;

    @GetMapping("/page")
    public Result getTeachPage(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String course,
            @RequestParam int pageNum,
            @RequestParam int pageSize) {

        List<Need> teaches;
        int totalCount;

        if (name != null && course != null) {
            // 根据名称和课程进行分页查询
            teaches = Service.findByNameAndCourse(name, course, pageNum, pageSize);
            totalCount = Service.countByNameAndCourse(name, course);
        } else if (name != null) {
            // 仅根据名称进行分页查询
            teaches = Service.findByName(name, pageNum, pageSize);
            totalCount = Service.countByName(name);
        } else if (course != null) {
            // 仅根据课程进行分页查询
            teaches = Service.findByCourse(course, pageNum, pageSize);
            totalCount = Service.countByCourse(course);
        } else {
            return Result.error("输入不能都唯为空");
        }

        // 构建返回数据
        Map<String, Object> response = new HashMap<>();
        response.put("list", teaches);
        response.put("total", totalCount);

        return Result.success(response);
    }

    @GetMapping("/selectByCourse")
    public Result selectByCourse(@RequestParam String course)
    {
       return Result.success(Service.findUserAndNeed(course));
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam String account, @RequestParam String course) {
        return Result.success(Service.findNeedByAccountAndCourse(account,course));
    }

    @GetMapping("/selectAll")
    public Result selectAll() {
        return Result.success(Service.findAllNeed());
    }

    @GetMapping("/selectByAccount")
    public Result selectByAccount(@RequestParam String account) {
        return Result.success(Service.findNeedByAccount(account));
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody Need need) {
        Service.insertNeed(need);
        return Result.success();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable int id) {
        Service.deleteNeed(id);
        return Result.success();
    }
}
